/*
    * Browser.Engine.trident - (boolean) True if the current browser uses the trident engine (e.g. Internet Explorer).
    * Browser.Engine.gecko - (boolean) True if the current browser uses the gecko engine (e.g. Firefox, or any Mozilla Browser).
    * Browser.Engine.webkit - (boolean) True if the current browser uses the webkit engine (e.g. Safari, Google Chrome, Konqueror).
    * Browser.Engine.presto - (boolean) True if the current browser uses the presto engine (e.g. Opera 9).
    * Browser.Engine.name - (string) The name of the engine.
    * Browser.Engine.version - (number) The version of the engine. (e.g. 950)
    * Browser.Plugins.Flash.version - (number) The major version of the flash plugin installed.
    * Browser.Plugins.Flash.build - (number) The build version of the flash plugin installed.
*/
function orderListApp()
{
	$$('.orderResetArchiveLink').addEvent('click', function(){
		var truth = confirm('Reverting this entry to the database sets the date of entry to be today and its expiry date 3 days later. If you want to extend the expiry date, please do so in the Active Orders module. This action cannot be undone. Do you still want to continue?');
		if(truth)
		{
			return true;
		}
		return false;
	});
	$$('.orderDeleteLink').addEvent('click', function(){
		var truth = confirm('You have chosen to deactivate this order from the active orders list and place it in the archive. This change will be permanent and cannot be undone. Do you still want to continue?');
		if(truth)
		{
			return true;
		}
		return false;
	});
	
	$$('.orderExtendLink').addEvent('click', function(){
		var conf = confirm('This will extend the expiry date of this entry to another date in the future. Do you still want to continue?');
		if(conf)
		{
			var ask = prompt('Please input how many days you wish to extend the expiry date');
			if(isNaN(ask))
			{
				alert('Please supply a valid number. No entry has been modified.');
			}
			else
			{
				if(!ask)
				{
					alert('Please supply a valid number. No entry has been modified.');
				}
				else
				{
					var locplz = this.get('alt') + '&extend='+ask;
					window.location = locplz;
				}
			}
			
			return false;
		}
		else
		{
			return false;
		}
	});
	
	$$('.orderResetApp').addEvent('click', function(){
		var conf = confirm('This will reset the specific order into pending and will delete any existing photograph the user has previously uploaded. Do you still want to continue?');
		if(conf)
		{
			var ask = prompt('Please input how many days you wish to extend the expiry date');
			if(isNaN(ask))
			{
				alert('Please supply a valid number. No entry has been modified.');
			}
			else
			{
				if(!ask)
				{
					alert('Please supply a valid number. No entry has been modified.');
				}
				else
				{
					var locplz = this.get('alt') + '&extend='+ask;
					window.location = locplz;
				}
			}
			
			return false;
		}
		else
		{
			return false;
		}
	});
	$$('.orderPaidLink').addEvent('click', function(){
		var conf = confirm('Continuing will mark this specific order as "Paid". Make sure you saved the image of the deposit slip in a safe location for future reference as this action cannot be undone. Do you still want to continue?');
		
		if(conf)
		{
			return true;
		}
		return false;
	});
	
	$$('.orderShippedLink').addEvent('click', function(){
		var conf = confirm('You have chosen to mark this specific order as "Shipped". This cannot be undone. Do you still want to continue?');
		
		if(conf)
		{
			var pick = false;
			if($('shipIndicator') !== null)
			{
				var x = $('shipIndicator').get('alt');
				if(x == 'pickup')
				{
					pick = true;
				}
			}
			
			if(pick)
			{
				var val = this.get('alt');
					redir = val + '&waybill='+'0';
					window.location = redir;
					return false;				
			}
			else
			{
				var gg = prompt('Please enter the Waybill number of the product you wish to ship.');
				if(gg == '' || !gg)
				{
					alert('You have not entered a valid waybill number. The entry was not saved.');
					return false;
				}
				else
				{
					var val = this.get('alt');
					redir = val + '&waybill='+gg;
					
					window.location = redir;
					return false;
				}
			}
		}
		return false;
	});
}

function mailingListApp()
{
	if($('unsub') !== null)
	{
		$$('.mailingList').addEvent('click', function(){
			window.location = this.get('rel');
		});
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function orderList()
{
	if($('navigators') !== null)
	{
		$$('.targets').slide('hide');
		$$('.item').addEvent('click', function(){
			$$('.targets').slide('out');
			$('target'+this.get('rel')).slide('toggle');
		});
	}
}

function cartMath()
{
	if($('totalItemQty') !== null)
	{
		$$('.deletebtns').addEvent('click', function(){
			var g = confirm('Deleting this entry cannot be undone. Do you want to continue?');
			if(g)
			{
				window.location = this.get('alt');
			}
		});
	
		$('changeForm').fade('hide');
	
		var allNoFields = $$('.qtySBox');
		var qtyFields = $$('.c');
		var shipBtns = $$('.shipRadios');
		var access = $$('.a');
		var accessPlus = 0;
		if(!access[0])
		{
			var accessPlus = 0;
		}
		else
		{
			var accessPlus = 1;
		}
		
		var totalItems = 0;
		var newVal = 0;
		if(qtyFields[0] !== null)
		{
			for (i=0; i<qtyFields.length; i++)
			{
				totalItems += parseFloat(qtyFields[i].get('value'));
			}
			totalItems += accessPlus;
			$('totalItemQty').innerHTML = totalItems;
			$('totalItemQtyF').set('value', totalItems);
			
			$$('.a').addEvent('change', function(){			
				$('changeForm').fade('in');
				$('sendForm').fade('out');
				
				if($('qtyHide'+this.get('alt')) !== null)
				{
					$('qtyHide'+this.get('alt')).set('value', parseFloat(this.get('value')));
				}
				
				var currTotal = parseFloat($('total'+this.get('alt')).get('value'));
				var newQty = parseFloat(this.get('value'));
				var oldQty = parseFloat($('dividr'+this.get('alt')).get('value'));
				
				newVal =  (currTotal/oldQty)*newQty ;
				$('dividr'+this.get('alt')).set('value', newQty);
				$('total'+this.get('alt')).set('value', newVal);
				
				var subtotal = 0;
				for (aa=0; aa<allNoFields.length; aa++)
				{
					//all totals.
					subtotal += parseFloat($('total'+allNoFields[aa].get('alt')).get('value'));
				}
				
				$('sTotal').innerHTML = addCommas(subtotal.toFixed(2));
				
				$('subTDiv'+this.get('alt')).innerHTML = 'P'+addCommas(newVal.toFixed(2));
				
				newVal = 0;
				
				var gTotal = parseFloat($('sTotalForm').get('value')) + subtotal;
				$('gTotalDisplay').innerHTML = addCommas(gTotal.toFixed(2));
				$('grandTotalForm').set('value', gTotal);
			});
			
			shipBtns.addEvent('click', function(){
				if($('sizeToSend') !== null)
				{
					$('sizeToSend').set('value', this.get('value'));
					$('shippingID').set('value', this.get('alt'));
				}
				totalItems = accessPlus;
				
				for (i=0; i<qtyFields.length; i++)
				{
					totalItems += parseFloat(qtyFields[i].get('value'));
				}
	
				var newShp = parseFloat(this.get('value')) * totalItems;
				
				$('shippingPrice').innerHTML = 'P'+addCommas(newShp.toFixed(2));
				
				$('sTotalForm').set('value', newShp);
				
				var subtotal = 0;
				for (aa=0; aa<allNoFields.length; aa++)
				{
					//all totals.
					subtotal += parseFloat($('total'+allNoFields[aa].get('alt')).get('value'));
				}
				
				var gTotal = parseFloat($('sTotalForm').get('value')) + subtotal;
				$('gTotalDisplay').innerHTML = addCommas(gTotal.toFixed(2));
				$('grandTotalForm').set('value', gTotal);
			});
			$$('.c').addEvent('change', function(){
				$('changeForm').fade('in');
				$('sendForm').fade('out');
				
				if($('qtyHide'+this.get('alt')) !== null)
				{
					$('qtyHide'+this.get('alt')).set('value', parseFloat(this.get('value')));
				}
				
				totalItems = accessPlus;
				
				for (i=0; i<qtyFields.length; i++)
				{
					totalItems += parseFloat(qtyFields[i].get('value'));
				}
				
				
				$('totalItemQty').innerHTML = totalItems;
				$('totalItemQtyF').set('value', totalItems);
				
				var currTotal = parseFloat($('total'+this.get('alt')).get('value'));
				var newQty = parseFloat(this.get('value'));
				var oldQty = parseFloat($('dividr'+this.get('alt')).get('value'));
				
				newVal =  (currTotal/oldQty)*newQty ;
				$('dividr'+this.get('alt')).set('value', newQty);
				$('total'+this.get('alt')).set('value', newVal);
				
				var subtotal = 0;
				for (aa=0; aa<allNoFields.length; aa++)
				{
					//all totals.
					subtotal += parseFloat($('total'+allNoFields[aa].get('alt')).get('value'));
				}
				
				$('sTotal').innerHTML = addCommas(subtotal.toFixed(2));
				
				$('subTDiv'+this.get('alt')).innerHTML = 'P'+addCommas(newVal.toFixed(2));
				
				newVal = 0;
				var shipPrice = 0;
				for (i=0; i<shipBtns.length; i++)
				{
					if(shipBtns[i].get('checked'))
					{
						shipPrice = parseFloat(shipBtns[i].get('value'));
					}
				}
				
				var newShp = shipPrice * totalItems;
				
				var gTotal = parseFloat($('sTotalForm').get('value')) + subtotal;
				$('gTotalDisplay').innerHTML = addCommas(gTotal.toFixed(2));
				$('grandTotalForm').set('value', gTotal);
				
				$('shippingPrice').innerHTML = 'P'+addCommas(newShp.toFixed(2));
				$('sTotalForm').set('value', newShp);
			});
			
			if($('mainSubmit') !== null)
			{
				$('mainSubmit').addEvent('submit', function(){
					var conf = confirm('You will receive a confirmation email upon submission of this form. However after submission, you cannot change your order details. Your order will automatically be cancelled if a photograph of the proof of payment is received.');
					
					if(conf)
					{
						if($('pickup').get('checked') == true)
						{
							var conf2 = confirm('Once you\'ve confirmed with a photograph of your proof of payment, you will receive a confirmation email regarding when you can pick up your order at ' + $('pickup').get('alt')+'. If you wish to have your orders shipped instead, click \'Cancel\' and change your shipping options. Your order will be saved once you click \'OK\'.');
							if(conf2)
							{
								//place order - pickup
								var xx = this.get('action');
								this.set('action', xx+'pickup');
							}
							else
							{
								return false;
							}
						}
						else if($('ownAdd').get('checked') == true)
						{
							var again = confirm('You\'ve chosen to ship your orders to your own address. Make sure the address you supplied upon registration is a valid address. Shipping charges will apply. Do you wish to continue?');
							if(again)
							{
								//place order - shipping
								var address = $('addressShopper').get('alt');
								var xx = this.get('action');
								var formattedAddress = address.replace('#', '_sharp_');
								this.set('action', xx+formattedAddress.replace(' ', '+'));
							}
							else
							{
								return false;
							}
						}
						else
						{
							var address = prompt('Please type in the address you want your purchases to be delivered to.');
							if(!address)
							{
								alert('A valid address is required for delivery orders. If you wish to pick your orders up yourself, please change your choices on the shipping options part of the page.');
								return false;
							}
							else if(address.length < 5)
							{
								alert('A valid address is required for delivery orders. If you wish to pick your orders up yourself, please change your choices on the shipping options part of the page.');
								return false;
							}
							else
							{
								var again = confirm('Only orders with valid addresses will be accepted, if your address is not valid, this order will be cancelled. To re-enter your address, please click \'Cancel\' and place your order again. Your order will be saved once you click \'OK\'.');
								if(again)
								{
									//place order - shipping
									var xx = this.get('action');
									var formattedAddress = address.replace('#', '_sharp_');
									this.set('action', xx+formattedAddress.replace(' ', '+'));
								}
								else
								{
									return false;
								}
							}			
						}
					}
					else
					{
						return false;
					}
				});
				
			}
		}
	}
}

function adminLinkInitiate()
{
	if($('adminContainer') !== null)
	{

		$('adminLinks').slide('hide');
		$('adminContainer').addEvent('mouseover',function(){
			$('adminLinks').slide('in');
		});
		$('adminContainer').addEvent('mouseout',function(){
			$('adminLinks').slide('out');
		});
		$$('.adminListener').addEvent('click', function(){
			divSlider(this.get('rel'));
		});
	}
	else
	{
		//doNothing();
	}
}

function productPage()
{
	if($('addCart') !== null)
	{
		$('addCart').addEvent('click', function(){
			var g = confirm('This item will be added to your bag. Do you want to continue?');
			if(g)
			{
				if(this.get('rel') == 'stay')
				{
					var f = confirm('The item has been added to your shopping cart. Do you want to review the items in your bag? Click OK to continue.');
					if(f)
					{
						//go to cart
						window.location = $('goCart').get('value')+$('itemID').get('value')+'|'+$('itemTable').get('value')+'|'+$('qty').get('value')+'|'+$('sizeOption').get('value')+'|'+$('rand').get('value');
					}
					else
					{
						//stay home
						window.location = $('stayPage').get('value')+$('itemID').get('value')+'|'+$('itemTable').get('value')+'|'+$('qty').get('value')+'|'+$('sizeOption').get('value')+'|'+$('rand').get('value');
					}
					
				}
				else
				{
					var f = confirm('The page will now redirect to your bag. Please fill in the information required to continue shopping. Your item will be added to your bag after the registration. Click OK to continue.');
					if(f)
					{
						//go to cart
						window.location = $('goCart').get('value')+$('itemID').get('value')+'|'+$('itemTable').get('value')+'|'+$('qty').get('value')+'|'+$('sizeOption').get('value')+'|'+$('rand').get('value');
					}
				}
			}
		});
	}
	$$('.prodBig').fade('hide');
	if($('pic1') !== null)
	{
		$('pic1').fade('show');
	}
	$$('.smallPix').addEvent('click', function(){
		var findThis = this.get('id');
		$$('.prodBig').fade('out');
		$(findThis.replace('sm', 'pic')).fade('in');
	});
	
	$$('.thumb').addEvent('click', function(){
		window.location = $('item'+this.get('alt')).get('href');
	});
}
function sizeFilters()
{
	var galleryClass = '';
	if($('mainImgTop') !== null)
	{
		galleryClass = $('mainImgTop').get('rel');
	}
	
	var adder = 0;
	
	$$('.sizeBox').addEvent('click', function(){
		if(this.getStyle('background-color') != '#444040')
		{
			this.setStyle('color', '#ffffff');
			this.setStyle('background-color', '#444040');
			sizesArray[this.get('rel')] = 1;
		}
		else
		{
			this.setStyle('color', '#444039');
			this.setStyle('background-color', '#fefbf6');
			sizesArray[this.get('rel')] = 0;
		}
		
		$$('.itemLink').tween('display','none');
		adder = 0;
		for (i=0; i<sSizes.length; i++)
		{
			if(sizesArray[sSizes[i]] == 1)
			{
				$$('.'+sSizes[i]).tween('display','block');
				adder = adder+1;
			}
		}
		if(adder == 0)
		{
			$$('.itemLink').tween('display','block');
		}
	});
}

function initMainPrevs()
{
	
	var saleDivs = $$('.sale');
	
	for (i=0; i<saleDivs.length; i++)
	{
		saleDivs[i].set('title', 'Click to view other items on sale!');
	}
	
	$$('.sale').addEvent('click', function(){
		window.location = $('saleLink').get('href');
	});
	
	if($('searchBar') !== null)
	{
		if($('tooltipSubs') !== null)
		{
			$('tooltipSubs').fade('hide');
		}
		$('searchSub').addEvent('click', function(){
			var bal = $('searchBar').get('value');
			if(bal != 'SEARCH' || bal == '')
			{
				window.location = $('searchSub').get('alt')+bal.replace(' ','+');
			}
			else
			{
				alert('Please specify a Search Term.');
			}
		});
		if($('searchBar').get('value') == '')
		{
			$('searchBar').set('value','SEARCH');
			$('searchBar').addEvent('focus', function(){
				if($('searchBar').get('value') == 'SEARCH')
				{
					$('searchBar').set('value', '');
				}
			});
			$('searchBar').addEvent('blur', function(){
				if($('searchBar').get('value') == '')
				{
					$('searchBar').set('value', 'SEARCH');
				}
			});
			
			$('subText').set('value', 'Your Email');
			$('subText').addEvent('focus', function(){
				if($('subText').get('value') == 'Your Email')
				{
					$('subText').set('value', '');
				}
				if($('tooltipSubs') !== null)
					{
						$('tooltipSubs').fade('in');
					}				
			});
			$('subText').addEvent('blur', function(){
				if($('subText').get('value') == '')
				{
					$('subText').set('value', 'Your Email');
				}
				if($('tooltipSubs') !== null)
				{
					$('tooltipSubs').fade('out');
				}
			});
		}
	}
}
function divSlider(id)
{
	$(id).slide('toggle');
}

window.addEvent('domready',function(){
	$$('.slider').slide('hide');
	initMainPrevs();
	sizeFilters();
	productPage();
	adminLinkInitiate();
	cartMath();
	mceActivate();
	orderList();
	mailingListApp();
	orderListApp();
	//procedural stuff
		$$('.linkButton').addEvent('click', function(){
			window.location = this.get('alt');
		});
		$$('.registered').addEvent('click', function(){
			if(this.get('alt') == 'reg')
			{
				this.set('alt', 'new');
				$('in').innerHTML = 'Don\'t have an account yet?';
				$('out').innerHTML = 'create one';
				$$('.hider').fade('out');
			}
			else
			{
				this.set('alt', 'reg');
				$('in').innerHTML = 'Already a registered user?';
				$('out').innerHTML = 'log in';
				$$('.hider').fade('in');
			}
			return false;			
		});
});